package com.qyhl.school.school.center.activity;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.school.R;
import com.qyhl.school.R2;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.school.SchoolReporterActBean;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class SchoolCenterActFragment extends BaseFragment implements SchoolCenterActContract.SchoolCenterActView {
    @BindView(R2.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;


    private SchoolCenterActPresenter mPresenter;

    private CommonAdapter<SchoolReporterActBean> commonAdapter;

    private List<SchoolReporterActBean> mDataList = new ArrayList<>();

    private String username;

    private int lastId = 0;

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_school_center_act, null);
    }

    public static SchoolCenterActFragment newInstance() {
        SchoolCenterActFragment fragment = new SchoolCenterActFragment();
        return fragment;
    }

    @Override
    protected void create() {
        loadMask.setStatus(LoadingLayout.Loading);

        BusFactory.getBus().register(this);

        mPresenter = new SchoolCenterActPresenter(this);

        username = CommonUtils.getInstance().getUserName();

        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setRefreshFooter(new ClassicsFooter(getContext()));
        refresh.setEnableLoadMore(true);

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        recyclerView.setAdapter(commonAdapter = new CommonAdapter<SchoolReporterActBean>(getContext(), R.layout.item_school_reporter_act_home, mDataList) {
            @Override
            protected void convert(ViewHolder holder, SchoolReporterActBean bean, int position) {
                RoundedImageView cover = holder.getView(R.id.cover);
                Glide.with(SchoolCenterActFragment.this)
                        .load(bean.getLogo())
                        .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                        .into(cover);

                holder.setText(R.id.title, bean.getTitle());

                holder.setText(R.id.address, bean.getAddress());

                holder.setVisible(R.id.sign_btn, false);

                holder.setText(R.id.num, bean.getReportCount() + "个小伙伴");

                if (bean.isReportOver()) {
                    holder.setImageResource(R.id.tag, R.drawable.school_new_home_reporter_end_tag);
                } else if (bean.isReportNotStart()) {
                    holder.setImageResource(R.id.tag, R.drawable.school_new_home_reporter_forecast_tag);
                } else {
                    holder.setImageResource(R.id.tag, R.drawable.school_new_home_reporter_tag);
                }

                if (StringUtils.isNotEmpty(bean.getEndDate())) {
                    holder.setText(R.id.date, bean.getStartDate() + "—" + bean.getEndDate());
                } else {
                    holder.setText(R.id.date, bean.getStartDate());
                }
            }
        });

        if (StringUtils.isEmpty(username)) {
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setErrorText("请先登录");
        } else {
            mPresenter.getList(username, lastId);
        }

    }


    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                if (StringUtils.isEmpty(username)) {
                    loadMask.setStatus(LoadingLayout.Error);
                    loadMask.setErrorText("请先登录");
                } else {
                    loadMask.setReloadButtonText("加载中...");
                    lastId = 0;
                    mPresenter.getList(username, lastId);
                }
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                lastId = 0;
                mPresenter.getList(username, lastId);
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getList(username, lastId);
            }
        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                ARouter.getInstance()
                        .build(ARouterPathConstant.SCHOOL_REPORTER_ACT_DETAIL)
                        .withInt("actId",mDataList.get(position).getId())
                        .withBoolean("isMine",true)
                        .navigation();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    @Override
    public void setList(List<SchoolReporterActBean> beanList, boolean isMore) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            mDataList.clear();
        }
        lastId = beanList.get(beanList.size() - 1).getId();
        mDataList.addAll(beanList);
        if (commonAdapter != null) {
            commonAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void setError(String msg, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
            if (!NetUtil.isNetworkAvalible(getContext())) {
                showToast("网络异常，请检查您的网络！", 4);
            } else if (msg.contains("暂无")) {
                showToast("暂无更多主题！", 4);
            } else {
                showToast(msg, 4);
            }
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setReloadButtonText("点击重试~");
            if (!NetUtil.isNetworkAvalible(getContext())) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.LoginMessage event) {
        if (event != null) {
            if (event.isLogin()) {
                username = CommonUtils.getInstance().getUserName();
                lastId = 0;
                mPresenter.getList(username, lastId);
            } else {
                loadMask.setStatus(LoadingLayout.Error);
                loadMask.setErrorText("请先登录");
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
    }

}
